package com.android.cl.coludtf.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.android.cl.coludtf.R;
import com.android.cl.coludtf.activity.base.BaseActivity;
import com.android.cl.coludtf.appcliation.MyAppcliation;
import com.android.cl.coludtf.model.BaseBO;
import com.android.cl.coludtf.service.asynctask.LoginTask;
import com.android.cl.coludtf.utils.Urls;
import com.android.cl.coludtf.utils.sharedPreferences.DatabaseHelper;
import com.android.cl.coludtf.utils.toast.ToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Login extends BaseActivity {
    BaseBO bo;
    LoginTask task;
    @BindView(R.id.Edt_password)
    EditText EdtPassword;
    @BindView(R.id.Edt_account)
    EditText EdtAccount;
    @BindView(R.id.Btn_login)
    Button BtnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        InitView(0);
    }

    /**
     * 初始化检查
     *
     * @param type：0：登录进来调用；1：自动登录失败调用
     */
    public void InitView(int type) {
        bo = DatabaseHelper.getBaseBO();
        if (type == 0 && bo.account != null && !"".equals(bo.account) && bo.password != null && !"".equals(bo.password)) {
            //登录
            task(bo.account, bo.password);
        } else {
            setContentView(R.layout.activity_login);
            ButterKnife.bind(this);
            EdtAccount.setText(bo.account);
            EdtPassword.setText(bo.password);
            InitData();
        }
    }

    private void InitData() {
        BtnLogin.setOnClickListener(v -> {
            String account = EdtAccount.getText().toString().trim();
            String psd = EdtPassword.getText().toString().trim();
            if (account == null || account.equals("")) {
                ToastUtil.showTextShort(MyAppcliation.context.getString(R.string.err_account));
            } else if (psd == null || psd.equals("")) {
                ToastUtil.showTextShort(MyAppcliation.context.getString(R.string.err_password));
            } else {
                //登录
                task(account, psd);

            }
        });
    }

    @OnClick(R.id.Btn_login)
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.Btn_login:

                break;
        }
    }

    /**
     * 登陆异步任务
     *
     * @param userName
     * @param userPassword
     */
    void task(String userName, String userPassword) {

        bo = DatabaseHelper.getBaseBO();
        task = new LoginTask(this, "请稍等", "正在登陆...");
        bo.maps = Urls.getDefaultConfigrationMap();
        bo.account = userName;
        bo.password = userPassword;
        bo.maps.put("username", userName);
        bo.maps.put("password", userPassword);
        bo.requestUrl = Urls.URL_LOGIN;
        task.execute(bo);
    }

}
